package com.ujs.servicemsm.service.impl;

import com.ujs.commonutils.constant.RedisKey;
import com.ujs.servicebase.exception.GuliException;
import com.ujs.servicemsm.service.MailService;
import com.ujs.servicemsm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangshihao
 * @create 2023-08-11 13:05
 */
@Service
public class MailServiceImpl implements MailService {
    /**
     * 注入邮件工具类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String sendMailer;


    @Override
    public void sendCode(String to) {
        String code = redisTemplate.opsForValue().get(RedisKey.KEY_EMAIL_CODE + to);
        if (StringUtils.isEmpty(code)) {
            String sixBitRandom = RandomUtil.getSixBitRandom();
            String text = "您的谷粒学苑验证码为：" + sixBitRandom + "。验证码将在五分钟内有效。";
            redisTemplate.opsForValue().set("login::" + to, sixBitRandom, 5, TimeUnit.MINUTES);
            sendTextMailMessage(to, "谷粒学苑验证码", text);
        }
    }

    /**
     * 发送纯文本邮件
     *
     * @param to      邮件接收方
     * @param subject 发送主题
     * @param text    邮件内容
     */
    public void sendTextMailMessage(String to, String subject, String text) {
        try {
            // true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            // 邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            // 邮件收信人
            mimeMessageHelper.setTo(to);
            // 邮件主题
            mimeMessageHelper.setSubject(subject);
            // 邮件内容
            mimeMessageHelper.setText(text);
            // 邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            // 发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + to);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "发送邮件失败：" + e.getMessage());
        }
    }
}
